import {
  TableContainer,
  Table,
  Thead,
  Tr,
  Th,
  Tbody,
  Td,
  Heading,
  Box,
  useColorModeValue,
  Badge,
  Progress,
  Text,
  Flex,
  Tooltip,
  VStack,
  HStack,
  Button,
} from '@chakra-ui/react';
import { useEvmWalletTokenTransfers } from '@moralisweb3/next';
import { useSession } from 'next-auth/react';
import { useEffect, useState } from 'react';
import { getEllipsisTxt } from 'utils/format';
import { useNetwork } from 'wagmi';
import type { FC } from 'react';
import request from 'utils/request';
// 模拟验证记录数据
interface VerificationRecord {
  credentialId: string;
  status: 'pending' | 'verifying' | 'completed' | 'failed';
  progress: number;
  startTime: string;
  completedTime?: string;
  issuer: string;
  verifier: string;
  result?: string;
}

const generateMockRecords = (): VerificationRecord[] => {
  const baseRecords: VerificationRecord[] = [
    {
      credentialId: '0x7d5f3e52f4f7e1b7f9c4e9d8a1b2c3d4e5f6a7b8',
      status: 'completed',
      progress: 100,
      startTime: '2024-03-15T10:00:00',
      completedTime: '2024-03-15T10:05:00',
      issuer: '教育部学位认证中心',
      verifier: '某公司人力资源部',
      result: '验证通过'
    },
    {
      credentialId: '0x9e8f7c6d5e4f3a2b1c0d9e8f7c6d5e4f3a2b1c0d',
      status: 'verifying',
      progress: 65,
      startTime: '2024-03-15T11:30:00',
      issuer: 'Amazon Web Services',
      verifier: '某科技公司技术部'
    },
    {
      credentialId: '0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b',
      status: 'pending',
      progress: 0,
      startTime: '2024-03-15T12:00:00',
      issuer: '某知名科技公司',
      verifier: '某创业公司'
    },
    {
      credentialId: '0x4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3',
      status: 'failed',
      progress: 100,
      startTime: '2024-03-14T15:00:00',
      completedTime: '2024-03-14T15:10:00',
      issuer: 'ETS',
      verifier: '某外企HR',
      result: '凭证已过期'
    },
    {
      credentialId: '0x5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4',
      status: 'completed',
      progress: 100,
      startTime: '2024-03-14T09:00:00',
      completedTime: '2024-03-14T09:15:00',
      issuer: 'Microsoft',
      verifier: '某互联网公司',
      result: '验证通过'
    },
    {
      credentialId: '0x6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5',
      status: 'verifying',
      progress: 45,
      startTime: '2024-03-15T14:00:00',
      issuer: 'Google Cloud',
      verifier: '某创新企业'
    },
    {
      credentialId: '0x7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6',
      status: 'completed',
      progress: 100,
      startTime: '2024-03-13T16:00:00',
      completedTime: '2024-03-13T16:30:00',
      issuer: 'IBM',
      verifier: '某金融科技公司',
      result: '验证通过'
    },
    {
      credentialId: '0x8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7',
      status: 'failed',
      progress: 100,
      startTime: '2024-03-12T11:00:00',
      completedTime: '2024-03-12T11:20:00',
      issuer: 'Oracle',
      verifier: '某银行',
      result: '签名无效'
    },
    {
      credentialId: '0x9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8',
      status: 'pending',
      progress: 0,
      startTime: '2024-03-15T15:00:00',
      issuer: 'Salesforce',
      verifier: '某咨询公司'
    },
    {
      credentialId: '0xa1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0',
      status: 'verifying',
      progress: 80,
      startTime: '2024-03-15T13:30:00',
      issuer: 'Adobe',
      verifier: '某设计公司'
    },
    {
      credentialId: '0xb2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1',
      status: 'completed',
      progress: 100,
      startTime: '2024-03-14T10:00:00',
      completedTime: '2024-03-14T10:20:00',
      issuer: 'SAP',
      verifier: '某制造企业',
      result: '验证通过'
    },
    {
      credentialId: '0xc3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2',
      status: 'pending',
      progress: 0,
      startTime: '2024-03-15T16:00:00',
      issuer: 'VMware',
      verifier: '某云服务商'
    },
    {
      credentialId: '0xd4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3',
      status: 'verifying',
      progress: 25,
      startTime: '2024-03-15T15:30:00',
      issuer: 'Red Hat',
      verifier: '某系统集成商'
    },
    {
      credentialId: '0xe5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4',
      status: 'completed',
      progress: 100,
      startTime: '2024-03-13T14:00:00',
      completedTime: '2024-03-13T14:15:00',
      issuer: 'Intel',
      verifier: '某芯片公司',
      result: '验证通过'
    },
    {
      credentialId: '0xf6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5',
      status: 'failed',
      progress: 100,
      startTime: '2024-03-12T09:00:00',
      completedTime: '2024-03-12T09:10:00',
      issuer: 'NVIDIA',
      verifier: '某AI公司',
      result: '数据不匹配'
    }
  ];
  return baseRecords;
};

const ERC20Transfers: FC = () => {
  const hoverTrColor = useColorModeValue('gray.100', 'gray.700');
  const { data } = useSession();
  const { chain } = useNetwork();
  const { data: transfers } = useEvmWalletTokenTransfers({
    address: data?.user?.address,
    chain: chain?.id,
  });
  const [records, setRecords] = useState<VerificationRecord[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const recordsPerPage = 10;

  useEffect(() => {
    const mockRecords = generateMockRecords();
    setRecords(mockRecords);
    request.get('home/auth-progress')
  }, []);

  useEffect(() => console.log('transfers: ', transfers), [transfers]);

  // 计算总页数
  const totalPages = Math.ceil(records.length / recordsPerPage);

  // 获取当前页的记录
  const getCurrentPageRecords = () => {
    const startIndex = (currentPage - 1) * recordsPerPage;
    const endIndex = startIndex + recordsPerPage;
    return records.slice(startIndex, endIndex);
  };

  const getStatusBadge = (status: VerificationRecord['status']) => {
    const statusConfig = {
      pending: { color: 'gray', text: '等待验证' },
      verifying: { color: 'blue', text: '验证中' },
      completed: { color: 'green', text: '验证完成' },
      failed: { color: 'red', text: '验证失败' }
    };
    const config = statusConfig[status];
    return <Badge colorScheme={config.color}>{config.text}</Badge>;
  };

  const formatTime = (timeString: string) => {
    return new Date(timeString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <>
      <Heading size="lg" marginBottom={6}>
        凭证验证记录
      </Heading>
      {records.length ? (
        <Box 
          borderWidth="1px" 
          borderColor={useColorModeValue('gray.200', 'gray.600')} 
          borderRadius="xl" 
          padding="24px 18px"
          bg={useColorModeValue('white', 'gray.800')}
          boxShadow="sm"
        >
          <TableContainer>
            <Table variant="simple" size="sm">
              <Thead>
                <Tr>
                  <Th width="18%" color={useColorModeValue('gray.700', 'gray.300')}>凭证 ID</Th>
                  <Th width="15%" color={useColorModeValue('gray.700', 'gray.300')}>发行方</Th>
                  <Th width="15%" color={useColorModeValue('gray.700', 'gray.300')}>验证方</Th>
                  <Th width="12%" color={useColorModeValue('gray.700', 'gray.300')}>状态</Th>
                  <Th width="15%" color={useColorModeValue('gray.700', 'gray.300')}>进度</Th>
                  <Th width="15%" color={useColorModeValue('gray.700', 'gray.300')}>时间</Th>
                  <Th width="10%" color={useColorModeValue('gray.700', 'gray.300')}>结果</Th>
                </Tr>
              </Thead>
              <Tbody>
                {getCurrentPageRecords().map((record, key) => (
                  <Tr 
                    key={key} 
                    _hover={{ bgColor: hoverTrColor }}
                    transition="all 0.2s"
                  >
                    <Td>
                      <Tooltip label={record.credentialId} placement="top">
                        <Text isTruncated maxW="200px" color={useColorModeValue('gray.700', 'gray.300')}>
                          {getEllipsisTxt(record.credentialId)}
                        </Text>
                      </Tooltip>
                    </Td>
                    <Td>
                      <Text isTruncated maxW="150px" color={useColorModeValue('gray.700', 'gray.300')}>
                        {record.issuer}
                      </Text>
                    </Td>
                    <Td>
                      <Text isTruncated maxW="150px" color={useColorModeValue('gray.700', 'gray.300')}>
                        {record.verifier}
                      </Text>
                    </Td>
                    <Td>
                      <Box whiteSpace="nowrap">
                        {getStatusBadge(record.status)}
                      </Box>
                    </Td>
                    <Td>
                      <Flex align="center" gap={2}>
                        <Progress
                          value={record.progress}
                          size="sm"
                          width="80px"
                          colorScheme={
                            record.status === 'failed' ? 'red' :
                            record.status === 'completed' ? 'green' : 'blue'
                          }
                          borderRadius="full"
                        />
                        <Text fontSize="xs" whiteSpace="nowrap" color={useColorModeValue('gray.700', 'gray.300')}>
                          {record.progress}%
                        </Text>
                      </Flex>
                    </Td>
                    <Td>
                      <Tooltip 
                        label={record.completedTime ? 
                          <VStack align="start" spacing={1}>
                            <Text>开始：{formatTime(record.startTime)}</Text>
                            <Text>完成：{formatTime(record.completedTime)}</Text>
                          </VStack> : 
                          '进行中'
                        } 
                        placement="top"
                      >
                        <Text fontSize="sm" isTruncated color={useColorModeValue('gray.700', 'gray.300')}>
                          {formatTime(record.startTime)}
                        </Text>
                      </Tooltip>
                    </Td>
                    <Td>
                      <Text isTruncated maxW="100px" color={useColorModeValue('gray.700', 'gray.300')}>
                        {record.result || '-'}
                      </Text>
                    </Td>
                  </Tr>
                ))}
              </Tbody>
            </Table>
          </TableContainer>
          
          {/* 分页控制器 */}
          <Flex justify="space-between" align="center" mt={4}>
            <Text fontSize="sm" color={useColorModeValue('gray.600', 'gray.400')}>
              共 {records.length} 条记录，第 {currentPage} / {totalPages} 页
            </Text>
            <HStack spacing={2}>
              <Button
                size="sm"
                onClick={() => setCurrentPage(1)}
                isDisabled={currentPage === 1}
                colorScheme="blue"
                _hover={{
                  transform: 'translateY(-1px)',
                  shadow: 'md'
                }}
                transition="all 0.2s"
              >
                首页
              </Button>
              <Button
                size="sm"
                onClick={() => setCurrentPage((prev) => prev - 1)}
                isDisabled={currentPage === 1}
                colorScheme="blue"
                _hover={{
                  transform: 'translateY(-1px)',
                  shadow: 'md'
                }}
                transition="all 0.2s"
              >
                上一页
              </Button>
              <Button
                size="sm"
                onClick={() => setCurrentPage((prev) => prev + 1)}
                isDisabled={currentPage === totalPages}
                colorScheme="blue"
                _hover={{
                  transform: 'translateY(-1px)',
                  shadow: 'md'
                }}
                transition="all 0.2s"
              >
                下一页
              </Button>
              <Button
                size="sm"
                onClick={() => setCurrentPage(totalPages)}
                isDisabled={currentPage === totalPages}
                colorScheme="blue"
                _hover={{
                  transform: 'translateY(-1px)',
                  shadow: 'md'
                }}
                transition="all 0.2s"
              >
                末页
              </Button>
            </HStack>
          </Flex>
        </Box>
      ) : (
        <Box>暂无验证记录</Box>
      )}
    </>
  );
};

export default ERC20Transfers;
